package com.xcity.game.item.drop;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.xcity.db.entity.Player;
import com.xcity.game.common.GameStaticConfig;
import com.xcity.game.item.drop.listener.DropListener;

import naga.x.util.CommonUtils;

/**
 * 权重掉落组
 * @author yang.li
 *
 */
public class WeightDropGroup extends RangeDrop implements DropGroup {

	protected List<WeightDrop> drops = new ArrayList<WeightDrop>();
	protected List<Drop> fixedDrops; // 固定掉落（必掉）
	
	public WeightDropGroup(int min, int max) {
		this.probability = GameStaticConfig.defaultChanceBase;
		this.min = min;
		this.max = max;
	}
	
	public List<Drop> getFixedDrops() {
		return fixedDrops != null ? fixedDrops : (fixedDrops = new ArrayList<Drop>(2));
	}
	
	public List<WeightDrop> getWeightDrops(){
		return drops;
	}
	
	@Override
	public void addDrop(Drop drop) {
		if (drop instanceof WeightDrop) {
			WeightDrop wd = (WeightDrop) drop;
			if (wd.weight > 0) {
				wd.weightStart = weight;
				weight += wd.weight; // 累加权重
				wd.weight = weight;
				drops.add(wd);
			} else {
				getFixedDrops().add(wd);
			}
		}
	}

	@Override
	protected void processDrop(Player player, String cause, DropListener listener) {
		Random rnd = RND;
		List<Drop> _fixedDrops = this.fixedDrops;
		if (_fixedDrops != null) {
			for (int i = 0; i < _fixedDrops.size(); i++) {
				_fixedDrops.get(i).drop(rnd, player, cause, listener);
			}
		}
		if (weight <= 0 || drops.isEmpty()) {
			return;
		}
		int n = CommonUtils.randomInt(rnd, min, max); // 确定掉落数量
		while (n-- > 0) {
			int w = rnd.nextInt(weight);
			Drop drop = CommonUtils.findInterval(drops, w);
			if (drop != null) {
				drop.drop(rnd, player, cause, listener);
			}
		}
	}

}
